<template>
	<text class="vi_timetips">
		{{showValue}}
	</text>
</template>

<script>
	export default{
		name:"viTimetips",
		props:{
			value:{
				type:[String,Number,null],
				default:""
			},
			text:{
				type:[Object,null],
				default:()=>({})
			},
			//自动刷新，每60秒。一般不需要
			autoRefresh:{
				type:[Boolean,null],
				default:false
			}
		},
		data(){
			return {
				delay:60000,		//刷新时间
				showValue:"",
				dicText:{
					just:"刚刚",
					minutesAgo:"分钟前",
					hoursAgo:"小时前",
					daysAgo:"天前",
					monthsAgo:"月前",
					yearsAgo:"年前"
				},
				refreshTimer:null,	//刷新定时器
			}
		},
		computed:{
			textSetting(){
				if(this.$api.isObject(this.text)){
					return Object.assign({},this.dicText,this.text)
				}
				return this.dicText
			}
		},
		methods:{
			//刷新显示
			refresh(){
				if(!this.value){
					this.showValue ="";
					return
				}
				//校验时间值
				let time = new Date(this.value).getTime();
				if(!time){
					this.showValue ="";
					return
				}
				let now = new Date().getTime(),
					diff = now - time,
					yearUnit = 31558150000,		//恒星年
					monthUnit = 2629845833,		//恒星年除以12
					dayUnit = 86400000,			//天
					hourUnit = 3600000,			//小时
					minuteUnit = 60000;			//分钟
				if(diff > yearUnit){
					//大于年
					this.showValue = parseInt(diff/yearUnit) +this.textSetting.yearsAgo
				}else if(diff > monthUnit){
					//大于月
					this.showValue = parseInt(diff/monthUnit) +this.textSetting.monthsAgo
				}else if(diff > dayUnit){
					//大于天
					this.showValue = parseInt(diff/dayUnit) +this.textSetting.daysAgo
				}else if(diff > hourUnit){
					//大于小时
					this.showValue = parseInt(diff/hourUnit) +this.textSetting.hoursAgo
				}else if(diff > minuteUnit){
					//大于分钟
					this.showValue = parseInt(diff/minuteUnit) +this.textSetting.minutesAgo
				}else{//刚刚
					this.showValue = this.textSetting.just
				}
				if(this.refreshTimer){
					clearTimeout(this.refreshTimer);
					this.refreshTimer = null;
				}
				if(this.autoRefresh){
					this.refreshTimer = setTimeout(()=>{
						this.refresh()
					}, 60000)
				}
			},
		},
		watch:{
			"value":{
				immediate:true,
				handler(newValue){
					this.refresh()
				}
			}
		}
	}
</script>

<style lang="scss">
.vi_timetips{
	
}
</style>